<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="dataForm" class="searchform" inline label-width="80px">
        <el-form-item label="用户名" prop="url">
          <el-input
            v-model="listQuery.name"
            class="filter-item"
            placeholder="用户名"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.email')" prop="url">
          <el-input
            v-model="listQuery.email"
            class="filter-item"
            placeholder="邮箱"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.telephone')" prop="url">
          <el-input
            v-model="listQuery.tel"
            class="filter-item"
            placeholder="联系电话"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.loginCode')" prop="url">
          <el-input
            v-model="listQuery.code"
            class="filter-item"
            placeholder="登陆代码"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <!--        <el-form-item label="NT用户名" prop="url">-->
        <!--          <el-input-->
        <!--            v-model="listQuery.nt_domain"-->
        <!--            class="filter-item"-->
        <!--            placeholder="NT用户名"-->
        <!--            style="width: 204px;"-->
        <!--            @keyup.enter.native="handleFilter"-->
        <!--          />-->
        <!--        </el-form-item>-->

        <el-form-item>
          <el-button v-waves class="filter-item" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" @click="handleFilterReset">
            {{$t('bs.reset')}}
          </el-button>
        </el-form-item>

      </el-form>

    </div>

    <div
      style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;"
    >
      <div style="display: flex;flex-direction: row;padding-bottom: 24px">
        <div style="flex: 1;display: flex;align-items: center">
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleCreate"
          >
            {{ $t('table.add') }}
          </el-button>
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleDeleteAll"
          >
            {{$t('bs.batchDelete')}}
          </el-button>
        </div>
        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
          <el-popover
            v-model="tablesetvisible"
            placement="bottom-start"
            width="160"
          >
            <div class="setcheckbox">
              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
              <el-checkbox
                v-for="(item,key) in fileds"
                :key="key"
                v-model="item.is_show"
                false-label="0"
                true-label="1"
              >
                {{ item.title }}
              </el-checkbox>
            </div>
            <div slot="reference" class="hoverbutton">
              <img src="/static/table/fiter.png">
              <span style="margin-left: 8px;color: #666666">筛选</span>
            </div>
          </el-popover>
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" width="55">
          <template slot-scope="{$index,row}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          type="selection"
          width="55"
        />

        <el-table-column v-if="fileds.name.is_show==1" label="用户名">
          <template slot-scope="{row}">
            {{ row.name }}
          </template>
        </el-table-column>
        <!--        <el-table-column v-if="fileds.pass.is_show==1" label="密码">-->
        <!--          <template slot-scope="{row}">-->
        <!--            {{ row.pass }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column v-if="fileds.email.is_show==1" :label="$t('bs.email')">
          <template slot-scope="{row}">
            {{ row.email }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.tel.is_show==1" :label="$t('bs.telephone')">
          <template slot-scope="{row}">
            {{ row.tel }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.code.is_show==1" :label="$t('bs.loginCode')">
          <template slot-scope="{row}">
            {{ row.code }}
          </template>
        </el-table-column>
        <!--        <el-table-column v-if="fileds.nt_domain.is_show==1" label="NT用户名">-->
        <!--          <template slot-scope="{row}">-->
        <!--            {{ row.nt_domain }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column v-if="fileds.head_pic.is_show==1" label="头像">-->
        <!--          <template slot-scope="{row}">-->
        <!--            {{ row.head_pic }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button circle icon="el-icon-edit" size="small" @click="handleUpdate(row)"/>

            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDelete([row.id])"
            >
              <el-button slot="reference" circle icon="el-icon-delete" size="small" style="margin-left: 8px"/>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page_no"
        :total="total"
        @pagination="getList"
      />

    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane :label="$t('bs.basicInformation')" name="1">
            <el-row :gutter="2">

              <el-col :span="12">
                <el-form-item :label="$t('bs.loginCode')" prop="code">
                  <el-input v-model="temp.code"/>
                </el-form-item>
              </el-col>
              <!--          <el-col :span="12">-->
              <!--            <el-form-item label="密码" prop="pass">-->
              <!--              <el-input v-model="temp.pass" type="password" />-->
              <!--            </el-form-item>-->
              <!--          </el-col>-->
              <el-col :span="12">
                <el-form-item label="菜单权限组" prop="role_id">
                  <el-select v-model="temp.role_id">
                    <el-option v-for="(item,key) in role_list" :key="key" :label="item.name" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <!--          <el-col :span="12">-->
              <!--            <el-form-item :label="$t('bs.templatePermissions')" prop="temp_role_id">-->
              <!--              <el-select v-model="temp.temp_role_id">-->
              <!--                <el-option v-for="(item,key) in temp_role_list" :key="key" :label="item.name" :value="item.id" />-->
              <!--              </el-select>-->
              <!--            </el-form-item>-->
              <!--          </el-col>-->
              <el-col :span="12">
                <el-form-item label="路由权限" prop="route_id">
                  <el-select v-model="temp.route_id">
                    <el-option v-for="(item,key) in route_list" :key="key" :label="item.name" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('bs.email')" prop="email">
                  <el-input v-model="temp.email"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="name">
                  <el-input v-model="temp.name"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('bs.telephone')" prop="tel">
                  <el-input v-model="temp.tel"/>
                </el-form-item>
              </el-col>

              <!--          <el-col :span="12">-->
              <!--            <el-form-item label="头像" prop="head_pic">-->
              <!--              <el-input v-model="temp.head_pic" />-->
              <!--            </el-form-item>-->
              <!--          </el-col>-->
              <!--          <el-col :span="24">-->
              <!--            <el-form-item label="NT用户名" prop="nt_domain">-->
              <!--              <el-input v-model="temp.nt_domain" />-->
              <!--            </el-form-item>-->
              <!--          </el-col>-->
              <el-col :span="12">
                <el-form-item :label="$t('bs.status')" prop="status">
                  <el-switch
                    v-model="temp.status"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item :label="$t('bs.allowLoginBackend')" prop="is_admin">
                  <el-switch
                    v-model="temp.is_admin"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item :label="$t('bs.notes')" prop="memo">
                  <el-input v-model="temp.memo" type="textarea"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="个性化权限" name="2">
            <div>
              <el-tabs v-model="activeName" @tab-click="handleChangeType">
                <el-tab-pane v-for="(item,key) in types " :key="key" style="min-height: 300px"
                             :label="item.dict_value" :name="item.dict_value">

                  <div style="width: 100%;height: 480px;overflow: auto">

                    <el-tree
                      v-if="item&&item.role"
                      :ref="item.id"
                      :data="item.role"
                      :expand-on-click-node="false"
                      :props="{children: 'children',label: 'name'}"
                      class="permission-tree"
                      node-key="id"
                    >
                      <span slot-scope="{ node, data }" class="custom-tree-node">
                        <span>{{ data.name }}</span>
                        <span>
                          <el-checkbox v-model="data.is_read" @change="changeRoleRead(data)" :true-label="1"
                                       :false-label="0" :disabled="data.disabled_read===1">{{$t('bs.read')}}</el-checkbox>
                          <el-checkbox v-model="data.is_write" @change="changeRoleWrite(data)" :true-label="1"
                                       :false-label="0" :disabled="data.disabled_write===1">{{$t('bs.write')}}</el-checkbox>
                          <el-checkbox v-model="data.is_display" @change="changeRoleDisplay(data)" :true-label="1"
                                       :false-label="0" :disabled="data.disabled_display===1">{{$t('bs.display')}}</el-checkbox>
                                     <el-checkbox v-model="data.is_down" @change="changeRoledown(data)" :true-label="1"
                                                  :false-label="0" :disabled="data.disabled_down===1">{{$t('bs.download')}}</el-checkbox>
                        <el-checkbox v-model="data.is_share" @change="changeRoleShare(data)" :true-label="1"
                                     :false-label="0" :disabled="data.disabled_share===1">{{$t('bs.share')}}</el-checkbox>
                        </span>
                      </span>
                    </el-tree>
                  </div>
                </el-tab-pane>
              </el-tabs>

            </div>

          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="dialogPvVisible"
               title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column label="Channel" prop="key"/>
        <el-table-column label="Pv" prop="pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, createData, updateData, delData, fetchDict} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import {parseTime} from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect'
import md5 from 'js-md5'
import _ from "lodash";
import {
  getTemplateRoleList,
  getTemplateRoleSet,
  getTemplateUserSet,
  saveMenuTemplate,
  saveUserTemplate
} from "@/api/template";
import UserDetail from "@/views/manger/userDetail.vue"; // secondary package based on el-pagination

export default {
  name: 'SlLogin',
  components: {UserDetail, CyTreeSelect, Pagination},
  directives: {waves},
  data() {
    return {
      activeTab: '1',
      checked: true,
      tablesetvisible: false,

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      role_list: [],
      temp_role_list: [],
      route_list: [],
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      queryMap: {},
      importanceOptions: ['CngP/MSE-TS1', 'CngP/MSE-TS2'],
      sortOptions: [{label: '启用', key: '+id'}, {label: '禁用', key: '-id'}],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        name: '',
        // pass: '',
        // old_pass: '',
        email: '',
        memo: '',
        role_id: '',
        temp_role_id: '',
        tel: '',
        id: '',
        code: '',
        //  nt_domain: '',
        status: '',
        // head_pic: '',
        dept_id: '',
        route_id: '',
        is_admin: ''
      },
      fileds: {
        name: {filed: 'name', title: '用户名', is_show: '1'},
        // pass: { filed: 'pass', title: '密码', is_show: '1' },
        email: {filed: 'email', title: '邮箱', is_show: '1'},
        tel: {filed: 'tel', title: '联系电话', is_show: '1'},
        code: {filed: 'code', title: '登陆代码', is_show: '1'}
        // nt_domain: { filed: 'nt_domain', title: 'NT用户名', is_show: '1' },
        // head_pic: { filed: 'head_pic', title: '头像', is_show: '1' }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        code: [{required: true, message: '此项不能为空', trigger: 'change'}],
        // pass: [{ required: true, message: '此项不能为空', trigger: 'change' }],
        role_id: [{required: true, message: '此项不能为空', trigger: 'change'}]
      },
      downloadLoading: false,
      activeName: '综合模板',
      types: [],
      types_bk: [],

    }
  },
  created() {
    this.getList()
    this.getRole()
    this.getRoute()
    this.getTplRole()
  },
  mounted() {
    this.getTpl()
  },
  methods: {
    async saveTplPri() {
      let data = []
      this.types.forEach((item) => {
        data = data.concat(this.getTreeNode(item.role))
      })
      const subdata = data.map((item) => {
        return {
          temp_id: parseInt(item.id),
          is_read: item.is_read,
          is_write: item.is_write,
          is_display: item.is_display,
          is_share: item.is_share,
          is_down: item.is_down,
          uu_id: item.uu_id,
          doc_id: parseInt(item.doc_id),
          inc_type: item.inc_type
        }
      })
      this.temp['data'] = subdata
      this.temp.user_id = parseInt(this.temp.id) || 0
      // this.temp.is_default = parseInt(this.temp.is_default)
      saveUserTemplate(this.temp).then((res) => {
        // this.listQuery.where = {}
        // this.getList()
        // this.dialogFormVisible = false
        return true
        // this.$notify({
        //     title: '成功',
        //     message: '创建成功',
        //     type: 'success',
        //     duration: 2000
        // })
      })
    },
    async getTpl() {
      const department = await fetchDict('模板分类')
      department.data.items.forEach((item) => {
        this.getTypeRole(0, item.dict_key).then((res) => {
          console.log('返回的数据', res)
          let resarr = res[0]
          if (res.length > 1) {
            resarr = []
            res.forEach((item) => {
              if (item && item.length > 0) {
                resarr.push(item[0])
              }
            })
          }

          console.log(item.dict_key + '每个角色role', resarr)
          item.role = _.cloneDeep(resarr)
        })
      })

      this.types = department.data.items
      this.types_bk = _.cloneDeep(this.types)

      console.log('最终数据', this.types_bk)
    },
    changeRoleRead(data) {
      var value = data.is_read;
      if (data.children && data.children.length > 0) {
        data.children.forEach((item) => {
          item.is_read = value;
          this.changeRoleRead(item)
        })
      }

    },
    changeRoleWrite(data) {
      var value = data.is_write;
      console.log("写改变", data.children)
      if (data.children && data.children.length > 0) {
        data.children.forEach((item) => {
          item.is_write = value;
          this.changeRoleWrite(item)
        })
      }
    },
    changeRoledown(data) {
      var value = data.is_down;
      if (data.children && data.children.length > 0) {
        data.children.forEach((item) => {
          item.is_down = value;
          this.changeRoledown(item)
        })
      }
    },
    changeRoleDisplay(data) {
      var value = data.is_display;
      if (data.children && data.children.length > 0) {
        data.children.forEach((item) => {
          item.is_display = value;
          this.changeRoleDisplay(item)
        })
      }
    },
    changeRoleShare(data) {
      var value = data.is_share;
      if (data.children && data.children.length > 0) {
        data.children.forEach((item) => {
          item.is_share = value;
          this.changeRoleShare(item)
        })
      }
    },
    async getTypeRole(role_id, inc_type) {
      console.log('参数', role_id, inc_type)
      const role = await getTemplateRoleList(role_id, inc_type)
      console.log('循环获取的权限', role.data.template)
      return role.data.template
    },
    handleChangeType(type) {
      console.log('类型', this.activeName, type)
    },
    getTreeNode(tree) {
      let data = []
      tree.forEach((item) => {
        data.push(item)
        if (item.children && item.children.length > 0) {
          data = data.concat(this.getTreeNode(item.children))
        }
      })
      return data
    },
    setTreeNode(tree, key, value) {
      tree.forEach((item) => {
        item[key] = value
        if (item.children && item.children.length > 0) {
          this.setTreeNode(item.children, key, value)
        }
      })
    },
    changeRead(val, item) {
      console.log('换了', val, item)

      this.setTreeNode(item.role, 'is_read', val)
      item.role = _.cloneDeep(item.role)
    },
    changeView(val, item) {
      this.setTreeNode(item.role, 'is_display', val)
      item.role = _.cloneDeep(item.role)
    },
    changeShare(val, item) {
      this.setTreeNode(item.role, 'is_share', val)
      item.role = _.cloneDeep(item.role)
    },
    changeWrite(val, item) {
      this.setTreeNode(item.role, 'is_write', val)
      item.role = _.cloneDeep(item.role)
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(this.multipleSelection.map(item => item.id))
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getTplRole() {
      this.listLoading = true
      fetchList({
        page_no: 1,
        limit: 1000,
        sort: 'id desc',
        where: {}
      }, 'sl_role_template').then(response => {
        if (response.data && response.data.items) {
          this.temp_role_list = response.data.items
          // this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    getRole() {
      this.listLoading = true
      fetchList({
        page_no: 1,
        limit: 1000,
        sort: 'id desc',
        where: {}
      }, 'sl_role').then(response => {
        if (response.data && response.data.items) {
          this.role_list = response.data.items
          // this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    getRoute() {
      this.listLoading = true
      fetchList({
        page_no: 1,
        limit: 1000,
        sort: 'id desc',
        where: {}
      }, 'sl_route_role').then(response => {
        if (response.data && response.data.items) {
          this.route_list = response.data.items
          // this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'sl_login').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      }
      this.getList()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({field: listkeys[i], operator: operator, value: value})
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({field: listkeys[i], operator: operator, value: value})
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {prop, order} = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        name: '',
        // pass: '',
        // old_pass: '',
        temp_role_id: '',
        email: '',
        memo: '',
        role_id: '',
        tel: '',
        id: '',
        code: '',
        //       nt_domain: '',
        status: '',
        // head_pic: '',
        dept_id: '',
        route_id: '',
        is_admin: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'login',
            add: this.temp
          }
          createData({data: [data]}, 'sl_login').then(async () => {
            this.listQuery.where = {}
            this.getList()
            this.dialogFormVisible = false
            const res = await this.saveTplPri();
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.old_pass = this.temp.pass
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      await this.setRoleData(row)
      await this.setUserData(row)

    },
    async setRoleData(row) {

      console.log("点击的row")
      var userPri = await getTemplateRoleSet(row.role_id)
      this.$nextTick(() => {
        this.types.forEach((item) => {
          this.setTreeNode(item.role, 'is_read', 0)
          this.setTreeNode(item.role, 'is_write', 0)
          this.setTreeNode(item.role, 'is_down', 0)
          this.setTreeNode(item.role, 'is_display', 0)
          this.setTreeNode(item.role, 'is_share', 0)
          this.setTreeNode(item.role, 'disabled_read', 0)
          this.setTreeNode(item.role, 'disabled_write', 0)
          this.setTreeNode(item.role, 'disabled_display', 0)
          this.setTreeNode(item.role, 'disabled_share', 0)
          this.setTreeNode(item.role, 'disabled_down', 0)
          console.log('组件ref', this.$refs[item.id])
          const data = this.getTreeNode(item.role)
          item.readall = true
          item.writeall = true
          item.viewall = true
          item.downall = true
          item.shareall = true;
          if (!userPri.data.items || userPri.data.items.length === 0) {
            item.readall = false
            item.writeall = false
            item.viewall = false
            item.downall = false
            item.shareall = false;
          }

          data.forEach((treeItem) => {
            if (userPri.data.items) {
              userPri.data.items.forEach((userItem) => {
                if (userItem.doc_id == treeItem.id) {

                  treeItem.is_read =userItem.is_read&&userItem.is_read==1?1:0
                  treeItem.is_write = userItem.is_write&&userItem.is_write==1?1:0
                  treeItem.is_display =userItem.is_display&&userItem.is_display==1?1:0
                  treeItem.is_share = userItem.is_share&&userItem.is_share==1?1:0
                  treeItem.is_down = userItem.is_down&&userItem.is_down==1?1:0

                  console.log("浴血彩凤",treeItem)

                  if (!treeItem.is_read ||treeItem.is_read == 0) {
                    item.readall = false;
                  } else {
                    treeItem.disabled_read = 1;
                  }
                  if (!treeItem.is_write ||treeItem.is_write == 0) {
                    item.writeall = false;
                  } else {
                    treeItem.disabled_write = 1;
                  }
                  if (!treeItem.is_display && treeItem.is_display == 0) {
                    item.viewall = false;
                  } else {
                    treeItem.disabled_display = 1;
                  }
                  if (!treeItem.is_down || treeItem.is_down == 0) {
                    item.downall = false;
                  } else {
                    treeItem.disabled_down = 1;
                  }
                  if (!treeItem.is_share ||treeItem.is_share == 0) {
                    item.shareall = false;
                  } else {
                    treeItem.disabled_share = 1;
                  }
                }

              })
            }
          })

          this.$refs[item.id][0].setCheckedKeys([])
        })
        this.types = _.cloneDeep(this.types)
        this.$refs['dataForm'].clearValidate()
      })

    },
    async setUserData(row) {
      var userPri = await getTemplateUserSet(row.id)
      this.$nextTick(() => {
        this.types.forEach((item) => {
          // this.setTreeNode(item.role, 'is_read', 0)
          // this.setTreeNode(item.role, 'is_write', 0)
          // this.setTreeNode(item.role, 'is_display', 0)
          // this.setTreeNode(item.role, 'is_down', 0)
          // this.setTreeNode(item.role, 'is_share', 0)
          console.log('组件ref', this.$refs[item.id])
          const data = this.getTreeNode(item.role)
          item.readall = true
          item.writeall = true
          item.viewall = true
          item.downall = true
          item.shareall = true;
          data.forEach((treeItem) => {
            if(userPri.data.items){
              userPri.data.items.forEach((userItem) => {
                if (userItem.doc_id == treeItem.id) {
                  treeItem.is_read =userItem.is_read&&userItem.is_read==1?1:0
                  treeItem.is_write = userItem.is_write&&userItem.is_write==1?1:0
                  treeItem.is_display =userItem.is_display&&userItem.is_display==1?1:0
                  treeItem.is_share = userItem.is_share&&userItem.is_share==1?1:0
                  treeItem.is_down = userItem.is_down&&userItem.is_down==1?1:0
                  if (!treeItem.is_read) {
                    item.readall = false;
                  }
                  if (!treeItem.is_write) {
                    item.writeall = false;
                  }
                  if (!treeItem.is_display) {
                    item.viewall = false;
                  }
                  if (!treeItem.is_down) {
                    item.downall = false;
                  }
                  if (!treeItem.is_share) {
                    item.shareall = false;
                  }
                }

              })
            }

          })
          this.$refs[item.id][0].setCheckedKeys([])
        })
        this.types = _.cloneDeep(this.types)
        this.$refs['dataForm'].clearValidate()
      })

    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if (this.temp.pass != this.temp.old_pass) {
          //   this.temp.pass = md5(this.temp.pass)
          // }

          const data = {
            modelname: 'login',
            update: this.temp
          }
          updateData({data: [data]}, 'sl_login').then(async () => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            const res = await this.saveTplPri();
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDelete(ids) {
      delData({id: ids.join(',')}, 'sl_login').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 280px;
}

.permission-tree {
  margin-bottom: 30px;

}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>

